/**
 */
package com.tjian.fafa.user.base;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tjian.fafa.user.R;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.chatServices.ChatService;
import com.tjian.fafa.user.base.chatServices.InitData;
import com.tjian.fafa.user.base.commons.GlobalMsgTypes;
import com.tjian.fafa.user.base.commons.GlobalStrings;
import com.tjian.fafa.user.base.friendRequest.FriendRequestService;
import com.tjian.fafa.user.base.mainBody.AskForUnsendThread;
import com.tjian.fafa.user.base.mainBody.MainBodyActivity;
import com.tjian.fafa.user.base.mainBody.MainBodyService;
import com.tjian.fafa.user.base.myNetwork.NetConnect;
import com.tjian.fafa.user.base.myNetwork.NetworkService;
import com.tjian.fafa.user.module.courier.activity.BaseActivity;
import com.tjian.fafa.user.module.user.CommonUser_fafa;

import net.oschina.app.bean.Constants;

import java.util.HashMap;
import java.util.Map;

/**
 */
public class MainActivity_login extends BaseActivity
{
    private String phone;
    private UserInfo userInfo;


    private String password;
    private NetConnect netConnect;

    private EditText account;
    private EditText password_EditText;
    private Button login_Button;
    private Button register_Button;
    private Button button_just_have_a_look;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_login);

        account = (EditText) findViewById(R.id.mainLoginEditAccount);
        password_EditText = (EditText) findViewById(R.id.mainLoginEditPassword);
        login_Button = (Button) findViewById(R.id.mainLoginBtn);
        register_Button = (Button) findViewById(R.id.main_btn_register);

        button_just_have_a_look = (Button) findViewById(R.id.id_just_have_a_look_button);

        password_EditText.setTypeface(Typeface.DEFAULT);/* this is to render the password edittext font to be default */
        password_EditText.setTransformationMethod(new PasswordTransformationMethod());

        //登录
        login_Button.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                initProgressDialog();//加载中的效果

                //乱分隔符登录
                MainActivity_login.this.tryLoginChaos();

                //json形式登录
                //MainActivity_login.this.tryLogin_json_fafa();
            }
        });

        register_Button.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent0 = new Intent(MainActivity_login.this, RegisterActivity.class);
                startActivity(intent0);
            }
        });

        button_just_have_a_look.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                ConnectedApp connectedApp = ConnectedApp.getInstance();
                connectedApp.clearListActivity();
                connectedApp.instantiateListActivity();
                gotoHomePage();
            }
        });
    }

    //乱码分隔符
    public void tryLoginChaos()
    {
        phone = account.getText().toString();
        password = password_EditText.getText().toString();

        if (phone.equals("") || password.length() < 5)
        {
            Toast.makeText(MainActivity_login.this, "请输入正确的用户名和密码！", Toast.LENGTH_LONG).show();
        }
        else
        {
            userInfo = new UserInfo(phone, 0, 0, 0, 0, 0, 0);




            //userInfo= new UserInfo();
            //userInfo.setPhone(phone);





            CloseAll.closeAll();



            // 与服务器建立连接
            NetworkService.getInstance().onInit(this);
            NetworkService.getInstance().setupConnection();
            if (NetworkService.getInstance().getIsConnected())
            {
                String userInfoString = userInfo.toString() + GlobalStrings.signinDivider + password + GlobalStrings.signinDivider;
                //mStrToSend:haoren&#&0&#&0&#&0&#&0&#&0&#&0&#&0&#&xx&#&xx&#&xx&#&imgs/avatar/2014/12/27/haoren.jpg&#&####!!!!&&haoren####!!!!&&








                //Gson gson = new Gson();
                //String userInfoString = gson.toJson(userInfo);


                NetworkService.getInstance().sendUpload(GlobalMsgTypes.msgHandShake, userInfoString);
            }
            else
            {
                NetworkService.getInstance().closeConnection();
                Toast.makeText(this, "连接服务器失败！", Toast.LENGTH_LONG).show();
                return;
            }
            InitData initData = InitData.getInitData();
            initData.start();
            try
            {
                initData.join();//initData执行完后，才能继续往下执行。
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            userInfo = initData.getUserInfo();
            if (userInfo.getId() < 0)
            {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                return;
            }

            ConnectedApp connectedApp = ConnectedApp.getInstance();
            connectedApp.setUserInfo(userInfo);
            //&#&1&#&0&#&0&#&1&#&1991&#&9&#&9&#&xx&#&xx&#&xx&#&imgs/avatar/2014/12/27/haoren.jpg&#&&#&
            connectedApp.clearListActivity();
            connectedApp.instantiateListActivity();

            //开启聊天服务
            tryStartChatService();

            gotoHomePage();
        }
    }

    //json登录
    public void tryLogin_json_fafa()
    {
        CommonUser_fafa commonUser_fafa = new CommonUser_fafa();

        Map paramMap = new HashMap();

        phone = account.getText().toString();
        password = password_EditText.getText().toString();


        if (phone.equals("") || password.length() < 5)
        {
            Toast.makeText(MainActivity_login.this, "请输入正确的用户名和密码！", Toast.LENGTH_LONG).show();
        }
        else
        {
            commonUser_fafa.setPhone(phone);
            commonUser_fafa.setPassword(password);


            // 与服务器建立连接
            NetworkService.getInstance().onInit(this);
            NetworkService.getInstance().setupConnection();
            if (NetworkService.getInstance().getIsConnected())
            {
                //JSONObject jsonObject = JSONObject.fromObject(commonUser_fafa);
                //JSONObject jsonStu = JSONObject.fromObject(student);
                //对象转成json后，覆盖原来的json,就可以测试新版的json方法
                //String userInfo_json = jsonObject.toString();


                Gson gson = new Gson();
                String userInfo_json = gson.toJson(commonUser_fafa);


                NetworkService.getInstance().sendUpload_json_fafa(GlobalMsgTypes.handShakeLogin_do, userInfo_json);
            }
            else
            {
                NetworkService.getInstance().closeConnection();
                Toast.makeText(this, "连接服务器失败！", Toast.LENGTH_LONG).show();
                return;
            }


            InitData initData = InitData.getInitData();
            initData.start();
            try
            {
                initData.join();//initData执行完后，才能继续往下执行。
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }


            userInfo = initData.getUserInfo();
            if (userInfo.getId() < 0)
            {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                return;
            }

            ConnectedApp connectedApp = ConnectedApp.getInstance();
            connectedApp.setUserInfo(userInfo);
            connectedApp.clearListActivity();
            connectedApp.instantiateListActivity();
            gotoHomePage();

        }
    }

    //跳转到首页。
    public void gotoHomePage()
    {
        Intent intent0 = new Intent(MainActivity_login.this, MainBodyActivity.class);
        startActivity(intent0);
        finish();
    }

    protected void tryStartChatService()
    {
        Intent intentTemp = new Intent(MainActivity_login.this, ChatService.class);
        startService(intentTemp);
        intentTemp = new Intent(MainActivity_login.this, FriendRequestService.class);
        startService(intentTemp);

        MainBodyService.getInstance().onReadMsg();
        MainBodyService.getInstance().onReadFrdReqNotif();
        MainBodyService.getInstance().onReadUnreadMsgAm();
        new AskForUnsendThread().start();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }

    public NetConnect getmNetCon()
    {
        return netConnect;
    }

    public void setmNetCon(NetConnect netConnect)
    {
        this.netConnect = netConnect;
    }


}